package com.example.ribbontest.command;

import com.example.ribbontest.domain.User;
import com.example.ribbontest.service.UserService;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 请求合并
 */
public class UserCollapseCommand extends HystrixCollapser<List<User>,User,Integer> {

    private UserService userService;
    private Integer userId;

    public UserCollapseCommand( UserService userService, Integer userId) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("userCollapseCommand")).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(100)));
        this.userService = userService;
        this.userId = userId;
    }

    @Override
    public Integer getRequestArgument() {
        return userId;
    }

    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Integer>> collapsRequests) {
        List<Integer> userIds = new ArrayList<>(collapsRequests.size());
        userIds.addAll(collapsRequests.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));
        return new UserBatchCommand(userService,userIds);
    }

    @Override
    protected void mapResponseToRequests(List<User> batchResponse, Collection<CollapsedRequest<User, Integer>> collapsRequests) {
        int count = 0;
        for(CollapsedRequest<User,Integer> collapsedRequest:collapsRequests)
        {
            User user = batchResponse.get(count++);
            collapsedRequest.setResponse(user);
        }

    }
}
